package cn.vawn.medical.controller;

import cn.vawn.base.consts.AppConsts;
import cn.vawn.base.controller.BaseController;
import cn.vawn.base.dto.ResponseResult;
import cn.vawn.base.util.Base64FileUtil;
import cn.vawn.base.util.MessageUtil;
import cn.vawn.base.util.StringUtil;
import cn.vawn.medical.dto.MecCurrentUnitermDTO;
import cn.vawn.medical.service.IOrganizationService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/wechat/personal")
public class WeChatPersonalController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(WeChatPersonalController.class);

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private MessageUtil messageUtil;

    /**
     * 导检服务-获取当前体检项状态
     *
     * @param organizationId
     * @param medicalNumber
     * @return
     */
    @RequestMapping(value = "/guide/current-uniterm", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<List<MecCurrentUnitermDTO>> getCurrentUniterm(@RequestParam("organizationId") Integer organizationId,
                                                                        @RequestParam("medicalNumber") String medicalNumber) {
        logger.info("try to guide current uniterm by organizationId: " + organizationId + ", medicalNumber" + medicalNumber);
        ResponseResult rr = null;
        if (organizationId == null || StringUtil.isEmpty(medicalNumber)) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "100002"));
            return rr;
        }
        // TODO 获取机构接口信息
        String apiUrl = "http://172.16.0.131:7022/api/tjgl/getprogress";
        // TODO 体检机构接口未找到 或 数据不全 或 请求参数不足
        if (StringUtil.isEmpty(apiUrl)) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300001"));
            return rr;
        }
        String responseString = "";
        String resultCode = "";
        JSONObject responseJsonObject = null;
        try {
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("tjbh", medicalNumber);
//            responseString = HttpClientUtil.httpGet(apiUrl, parameter);
            responseString = "{\"resultcode\":\"0\",\"reason\":\"success\",\"result\":[{\"tjbh\":\"136401910000891\",\"name\":\"周建荣\",\"package\":\"2014新个人体检(男)A\",\"itemcode\":\"220301001-2\",\"itemname\":\"彩色多普勒超声-腹部\",\"sl\":\"1\",\"zt\":\"0\"},{\"tjbh\":\"136401910000891\",\"name\":\"周建荣\",\"package\":\"2014新个人体检(男)A\",\"itemcode\":\"220201001B\",\"itemname\":\"单脏器彩色多普勒超声检查\",\"sl\":\"1\",\"zt\":\"0\"},{\"tjbh\":\"136401910000891\",\"name\":\"周建荣\",\"package\":\"2014新个人体检(男)A\",\"itemcode\":\"T00008\",\"itemname\":\"B超检查（甲状腺）\",\"sl\":\"1\",\"zt\":\"0\"}]}";
            responseJsonObject = JSONObject.fromObject(responseString);
            resultCode = responseJsonObject.getString("resultcode");
        } catch (Exception ex) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300002"));
            return rr;
        }
        // TODO 接口返回值转换
        if ("0".equals(resultCode)) {
            // 返回成功后数据转换
            List<MecCurrentUnitermDTO> mecCurrentUnitermDTOList = new ArrayList();
            try {
                JSONArray resultData = responseJsonObject.getJSONArray("result");
                if (resultData != null && !resultData.isEmpty()) {
                    MecCurrentUnitermDTO mecCurrentUnitermDTO = null;
                    for (int i = 0; i < resultData.size(); i++) {
                        JSONObject resultDataItem = resultData.getJSONObject(i);
                        mecCurrentUnitermDTO = new MecCurrentUnitermDTO();
                        mecCurrentUnitermDTO.setMedicalNumber(resultDataItem.getString("tjbh"));
                        mecCurrentUnitermDTO.setSetMealName(resultDataItem.getString("package"));
                        mecCurrentUnitermDTO.setItemCode(resultDataItem.getString("itemcode"));
                        mecCurrentUnitermDTO.setItemName(resultDataItem.getString("itemname"));
                        mecCurrentUnitermDTO.setStatus(resultDataItem.getString("zt"));
                        mecCurrentUnitermDTOList.add(mecCurrentUnitermDTO);
                    }
                }
                rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, "", mecCurrentUnitermDTOList);
            } catch (Exception ex) {
                rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300004"));
            }
        } else {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300003"));
        }
        return rr;
    }

    /**
     * 报告查询-获取体检报告的pdf格式（pdf to image）
     *
     * @param paramMap
     * @return
     */
    @RequestMapping(value = "/report/pdf", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Map<String, Object>> getReportOfPdfInfo(Map<String, String> paramMap) {
        logger.info("try to report pdf by " + paramMap);
        // 请求参数
        Integer organizationId = StringUtil.notEmpty(paramMap.get("organizationId")) ? Integer.parseInt(paramMap.get("organizationId")) : null;
        String medicalNumber = paramMap.get("medicalNumber");
        ResponseResult rr = null;
        if (organizationId == null || StringUtil.isEmpty(medicalNumber)) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "100002"));
            return rr;
        }
        // TODO 获取机构接口信息
        String apiUrl = "http://services.ikang.com/ikang-service/rs/cooperation/findReportInfo";
        // TODO 体检机构接口未找到 或 数据不全 或 请求参数不足
        if (StringUtil.isEmpty(apiUrl)) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300001"));
            return rr;
        }
        String responseString = "";
        String resultCode = "";
        JSONObject responseJsonObject = null;
        try {
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("cardnumber", "");
            parameter.put("workno", medicalNumber);
            parameter.put("onlycode", "");
            parameter.put("signature", "");
            parameter.put("version", "");
//            responseString = HttpClientUtil.httpGet(apiUrl, parameter);
            // TODO pdf演示文件
            String base64Pdf = Base64FileUtil.encodeBase64File(RequestContext.class.getResource("/").getFile() + "/test.pdf");
            responseString = "{\"code\":\"1\",\"message\":\"" + base64Pdf + "\",\"list\":null}";
            responseJsonObject = JSONObject.fromObject(responseString);
            resultCode = responseJsonObject.getString("code");
        } catch (Exception ex) {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300002"));
            return rr;
        }
        // TODO 接口返回值转换
        if ("1".equals(resultCode)) {
            // 返回成功后数据转换
            try {
                String pdfBase64String = responseJsonObject.getString("message");
                String imageBase64String = "";
                if (StringUtil.notEmpty(pdfBase64String)) {
                    imageBase64String = Base64FileUtil.pdfToImageBase64(pdfBase64String, null);
                }
                rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, "", imageBase64String);
            } catch (Exception ex) {
                rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300004"));
            }
        } else {
            rr = getCommonErrorResponse(messageUtil.getMessage(getLanguage(), "300003"));
        }
        return rr;
    }

    /**
     * 报告查询-获取体检报告的文本格式
     *
     * @return
     */
    @RequestMapping(value = "/report/text", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Map<String, Object>> getReportOfTextInfo() {
        return null;
    }
}
